import { getUserFunListByUserDDId } from "@/api/dd";
import { requestAuthCode } from "@/libs/dingding";
import type { ActionContext } from "vuex";
import { RootState } from "../";
import { setSession } from "@/libs/sessionStorage";
import { ant_design_vue } from "@/libs/global/antDesignVue";
let { message } = ant_design_vue

export type DingDingState = {
  userInfo: User.Info
}

export type DingDingContext = ActionContext<DingDingState, RootState>

const state: DingDingState = {
  userInfo: {
    roleLevel: 3,
    avatar: "",
    deptId: '',
    deptloaderId: "",
    deptName: "",
    scoreWeight: undefined,
    userId: "",
    userName: "",
  }
}

const mutations = {
  SETUSERINFO(state: DingDingState, data: User.Info) {
    state.userInfo = data
  }
}

const actions = {
  requestAuthCode({ state, rootState }: DingDingContext) {
    return new Promise((resolve: (value: { userInfo: User.Info, userFuns: Pm.UserFun[] }) => void, reject: (err: false) => void) => {
      requestAuthCode()
        .then(userInfo => {
          state.userInfo = userInfo
          setSession('userDDId', userInfo.userId)

          getUserFunListByUserDDId({ userDDId: userInfo.userId })
            .then(res => {
              rootState.aside.userAsideList = res.data

              const parentPath = location.href.replace(/^(http|https|ws|wss):\/\/(\w+\.*)+\:?([0-9]{4})?(\/\#)?(\/\w+)?([\/|\w]*)(\?[\w|\=|\&]+)*/g, '$5').substring(1)

              console.log('dingding actions requestAuthCode parentPath', parentPath);

              // 获取页面路由中的父路由
              rootState.aside.selectedKeys = [parentPath]

              /**不能在这里跳转，不然有些携带参数的路由会丢失参数 */
              // router.push({
              //   name: parentPath
              // })
              resolve({ userInfo, userFuns: res.data })
            })
            .catch(err => {
              message.error({
                content: '界面配置获取失败'
              })
              reject(false)

            })
        })
        .catch(err => {
          reject(false)
        })
    })
  }
}

const getters = {
  ddUserInfo: (state: DingDingState) => state.userInfo
}

export default {
  namespaced: true, // 声明命名空间
  state,
  mutations,
  actions,
  getters
}
